/*
 * Receiver.java
 *
 * Created on 18 lipiec 2007, 12:25
 *
 */

package pl.krakow.ae.knp.wikiboard.communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.SocketException;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.ParsingException;
import pl.krakow.ae.knp.wikiboard.gui.userslist.UsersListInterface;
import pl.krakow.ae.knp.wikiboard.xml.UserXML;

/**
 *
 * @author slawek
 */
public class Receiver extends Thread {
    
    private ObjectInputStream in;
    private UsersListInterface usersList;
    
    /** Creates a new instance of Receiver */
    public Receiver(ObjectInputStream in) {
        start();
        this.in = in;
    }
    
    public void run() {
        try {
            while(true) {
                Object object = in.readObject();
                if(object instanceof String) 
                    stringToXOM( (String)object );                
            }

        } catch (SocketException ex){
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } finally {
            try {
                in.close();
                usersList.clearAll();
                usersList.refresh();

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    private void stringToXOM(String xmlString) {
        try {
            Document response = new Builder().build(xmlString, null);
            String actionType = response.getRootElement().getAttribute("type").getValue();
            if( actionType.equals("login") )
                usersList.addUser( new UserXML( response.getRootElement().getFirstChildElement("user") ).getName() );
            else if( actionType.equals("logout") )
                usersList.removeUser( new UserXML( response.getRootElement().getFirstChildElement("user") ).getName());
            usersList.refresh();
        } catch (ParsingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public void addListener(UsersListInterface usersList) {
        this.usersList = usersList;
    }
}
